<template>
  <div class="certificate-container">
    <!-- 搜索表单 -->
    <div class="custom-form">
      <div class="form-item">
        <label style="width: 80px">课程名称</label>
        <el-input
          v-model="searchForm.name"
          placeholder="请输入课程名称"
          clearable
        />
      </div>
      <div class="form-item">
        <label style="width: 80px">考试时间</label>
        <el-date-picker
          v-model="searchForm.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="x"
        />
      </div>
      <div class="form-item buttons">
        <el-button type="primary" @click="handleSearch" icon="Search"
          >搜索</el-button
        >
        <el-button type="info" @click="resetSearch" icon="Refresh"
          >重置</el-button
        >
      </div>
    </div>

    <!-- 证书列表 -->
    <div class="certificate-list">
      <el-empty
        v-if="certificateList.length === 0"
        description="暂无证书记录"
      />

      <el-card
        v-for="item in certificateList"
        :key="item.id"
        class="certificate-card"
      >
        <div class="certificate-header">
          <h3>{{ item.subjectName }} 考试证书</h3>
          <el-tag type="success">已通过</el-tag>
        </div>

        <div class="certificate-content">
          <div class="certificate-info">
            <p><strong>考生姓名：</strong>{{ item.name }}</p>
            <p><strong>考试科目：</strong>{{ item.subjectName }}</p>
            <p><strong>考试分数：</strong>{{ item.score }}分</p>
            <p><strong>考试用时：</strong>{{ formatTime(item.usedTime) }}</p>
            <p v-if="item.testNum > 0">
              <strong>考试题数：</strong>{{ item.testNum }}题
            </p>
            <p><strong>考试时间：</strong>{{ formatDateTime(item.endTime) }}</p>
          </div>
          <div class="certificate-actions">
            <el-button type="primary" @click="printCertificate(item)">
              <el-icon><Printer /></el-icon>
              打印证书
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import subjectTestApi from "@/api/subject/test";

// 响应式数据
const certificateList = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

const searchForm = reactive({
  name: "",
  timeRange: [],
});

// 计算属性：获取开始和结束时间
const startTime = computed(() => {
  return searchForm.timeRange && searchForm.timeRange.length > 0
    ? searchForm.timeRange[0]
    : new Date("2000-01-01").getTime();
});

const endTime = computed(() => {
  return searchForm.timeRange && searchForm.timeRange.length > 1
    ? searchForm.timeRange[1]
    : new Date("2099-12-31").getTime();
});

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return "";
  return dateTimeString.replace("T", " ");
};

// 格式化考试用时
const formatTime = (timeString) => {
  if (!timeString) return "";
  // 假设timeString格式为 "HH:mm:ss"
  return timeString;
};

// 获取证书列表
const fetchCertificates = async () => {
  try {
    const params = {
      currentPage: currentPage.value,
      pageSize: pageSize.value,
      startTime: startTime.value,
      endTime: endTime.value,
      name: searchForm.name || "",
    };

    const [listRes, countRes] = await Promise.all([
      subjectTestApi.getPassedList(params),
      subjectTestApi.getPassedCount({
        startTime: startTime.value,
        endTime: endTime.value,
        name: searchForm.name || "",
      }),
    ]);

    certificateList.value = listRes.data;
    total.value = countRes.data;
  } catch (error) {
    console.error("获取证书列表失败:", error);
    ElMessage.error("获取证书列表失败");
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchCertificates();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = "";
  searchForm.timeRange = [];
  currentPage.value = 1;
  fetchCertificates();
};

// 分页
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchCertificates();
};

// 打印证书
const printCertificate = (certificate) => {
  // 创建打印内容
  const printWindow = window.open("", "_blank");
  printWindow.document.write(`
    <html>
      <head>
        <title>${certificate.subjectName} 考试证书</title>
        <style>
          body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 20px;
          }
          .certificate {
            width: 800px;
            margin: 0 auto;
            padding: 30px;
            border: 2px solid #1989fa;
            text-align: center;
          }
          .certificate-title {
            font-size: 28px;
            color: #1989fa;
            margin-bottom: 30px;
          }
          .certificate-content {
            text-align: left;
            margin: 20px 0;
            font-size: 16px;
            line-height: 1.8;
          }
          .certificate-footer {
            margin-top: 50px;
            text-align: right;
          }
          .certificate-seal {
            margin-top: 20px;
            font-style: italic;
            color: #1989fa;
          }
          @media print {
            body {
              padding: 0;
            }
          }
        </style>
      </head>
      <body>
        <div class="certificate">
          <h1 class="certificate-title">${
            certificate.subjectName
          } 考试合格证书</h1>
          <div class="certificate-content">
            <p>兹证明 <strong>${certificate.name}</strong> 在 ${formatDateTime(
    certificate.endTime
  )} 参加了 <strong>${certificate.subjectName}</strong> 考试，成绩为 <strong>${
    certificate.score
  }</strong> 分，考试合格。</p>
            <p>考试用时：${formatTime(certificate.usedTime)}</p>
            <p>考试题数：${certificate.testNum}题</p>
          </div>
          <div class="certificate-footer">
            <p>颁发日期：${formatDateTime(certificate.endTime)}</p>
            <div class="certificate-seal">E-Learning 在线学习平台</div>
          </div>
        </div>
      </body>
    </html>
  `);
  printWindow.document.close();

  // 延迟打印，确保内容已加载
  setTimeout(() => {
    printWindow.print();
  }, 500);
};

// 生命周期钩子
onMounted(() => {
  fetchCertificates();
});
</script>

<style scoped>
.certificate-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
}

.custom-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 10px;
}

.form-item label {
  margin-right: 8px;
  font-size: 14px;
  color: #606266;
}

.buttons {
  display: flex;
  gap: 10px;
}

.certificate-list {
  margin-bottom: 20px;
}

.certificate-card {
  margin-bottom: 20px;
}

.certificate-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.certificate-header h3 {
  margin: 0;
  color: #303133;
}

.certificate-content {
  display: flex;
  justify-content: space-between;
}

.certificate-info {
  flex: 1;
}

.certificate-info p {
  margin: 8px 0;
  color: #606266;
}

.certificate-actions {
  margin-top: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
